package org.example.controller;

import org.example.Service.UserService;
import org.example.config.SessionManager;
import org.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //跳转到登录页面
    @RequestMapping("/tologin")
    public String tologin() {
        return "login";
    }

    //登录
    @RequestMapping("/login")
    public String login(int user_id, String userpwd, Model model, HttpSession session) {
        User user = userService.selectUserByID(user_id);
        System.out.println(user);
        SessionManager.setSession(session);
        if (user != null && userpwd.equals(user.getUserpwd())) {
            SessionManager.setLoginInfo(user.getUsername(), user_id);
            model.addAttribute("username", user.getUsername());
            return "allProduct";
        } else {
            String err = "用户名或者密码有误！";
            model.addAttribute("err", err);
            return "login";
        }
    }

    //注销
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("userInfo");
        return "tologin";
    }
}
